package com.buttonpay.home;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

import com.buttonpay.AppData;
import com.buttonpay.HttpConn;
import com.buttonpay.MD5Generator;
import com.buttonpay.home.TransactionHistory.TransactionQuery;

public class GetTransactionRunnable implements Runnable 
{
	String refNo=null,currentDate=null,previousDate=null;
	boolean lastTransactionSearch,transactionQuerySearch;
	Context mContext;
	ProgressDialog pd= null;
	Handler handler= null;
	MD5Generator md5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	ArrayList<TransactionDetails> transactionArray;
	TransactionQuery transactionQueryDialog;
	
	ArrayList<String> 
		ProviderProductRequestID,ProductType,RequestType,
		ProviderAuditID,RequestTime,Product,ProductCode,
		Currency,Batch,ReferenceNumber,TopUpValue,TopUpValueRes,
		TopUpValuePro,TransactionResponseCode,TransactionResponseDescription;
	
	public GetTransactionRunnable(TransactionQuery transactionQueryDialog, Context context,ProgressDialog pd,Handler handler, String RefNo) 
	{	
		this.mContext=context;
		this.pd=pd;
		this.handler=handler;
		this.refNo=RefNo;
		this.transactionQueryDialog=transactionQueryDialog;
		transactionQuerySearch=true;
		lastTransactionSearch=false;
		
	}
	 
	 

	public GetTransactionRunnable(Context context,
			ProgressDialog pd, Handler handler,String currentDate,String previousDate) 
	{
		this.mContext=context;
		this.pd=pd;
		this.handler=handler;
		this.currentDate=currentDate;
		this.previousDate=previousDate;
		System.out.println("Current Date:"+this.currentDate+
							"Previous Date:"+this.previousDate);
		lastTransactionSearch=true;
		transactionQuerySearch=false;
	}



	public void run() 
	{
		
		
		 		try
				{
		 			String URL;
 					
		 			if(transactionQuerySearch)//do search for reference number
		 			{
			 			String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+"|"+"|"+"|"+refNo +"|"+
										AppData.getUserInfo().getpublickey() ));
						URL=AppData.hostURL+"/WebService/iTopUp/agentapp.php/TransactionDetails/LoginId/"+AppData.getUserInfo().getLoginID()+
									"/RecordLimit/"+""+"/StartTime/"+"/EndTime/"+"/ReferenceNumber/"+refNo 
			                     +"/Checksum/"+checksum;
		 			}
		 			else//do search for transaction between date
		 			{
		 				  /* String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+"|"+"|"+"|"+refNo +"|"+
								AppData.getUserInfo().getpublickey() ));
		 				   URL=AppData.hostURL+"/WebService/iTopUp/agentapp.php/TransactionDetails/LoginId/"+AppData.getUserInfo().getLoginID()+
							"/RecordLimit/"+""+"/StartTime/"+"/EndTime/"+"/ReferenceNumber/"+refNo 
							+"/Checksum/"+checksum;*/
		 				  String checksum=md5Generator.MD5(md5Generator.SHA1(AppData.getUserInfo().getLoginID()+"|"+"|"+previousDate+"|"+currentDate+"|"+""+"|"+
							AppData.getUserInfo().getpublickey() ));
						  URL=AppData.hostURL+"/WebService/iTopUp/agentapp.php/TransactionDetails/LoginId/"+AppData.getUserInfo().getLoginID()+
						 "/RecordLimit/"+""+"/StartTime/"+previousDate+"/EndTime/"+currentDate+"/ReferenceNumber/"
	                     +"/Checksum/"+checksum;
		 				   
		 			}
					

					System.out.println("URL===>\n"+URL);
		            String response=httpConn.createHttpConn(URL);
		            System.out.println("Response:"+response);
		            
		            final JSONObject jsonObject=new JSONObject(response);
		            JSONArray jsonArray;
		            
		            if(jsonObject.getString("ResponseCode").equals("000")&&jsonObject.getString("ResponseDescription").equals("Successfull"))
					{
		            	ProviderProductRequestID=new ArrayList<String>();
		            	ProductType=new ArrayList<String>();
		            	RequestType=new ArrayList<String>();
						ProviderAuditID=new ArrayList<String>();
						RequestTime=new ArrayList<String>();
						Product=new ArrayList<String>();
						ProductCode=new ArrayList<String>();
						Currency=new ArrayList<String>();
						Batch=new ArrayList<String>();
						ReferenceNumber=new ArrayList<String>();
						TopUpValue=new ArrayList<String>();
						TopUpValueRes=new ArrayList<String>();
						TopUpValuePro=new ArrayList<String>();
						TransactionResponseCode=new ArrayList<String>();
						TransactionResponseDescription=new ArrayList<String>();
						
						if(jsonObject.has("ProviderProductRequestID"))
						{
						     jsonArray=jsonObject.getJSONArray("ProviderProductRequestID");
						     System.out.println("Length of ProviderProductRequestID:"+jsonArray.length()+
	                                  "\ngetting ProviderProductRequestID");
						      for(int i=0;i<jsonArray.length();i++)
				              {
								ProviderProductRequestID.add(jsonArray.getString(i));
				              }
						}
						if(jsonObject.has("ProductType"))
			            {	
			                jsonArray=jsonObject.getJSONArray("ProductType");
			                System.out.println("Length of ProductType:"+jsonArray.length()+
			                		"\ngetting ProductType");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	ProductType.add(jsonArray.getString(i));
			                }
			            }
						if(jsonObject.has("RequestType"))
			            {
			                jsonArray=jsonObject.getJSONArray("RequestType");
			                System.out.println("Length of RequestType:"+jsonArray.length()+
			                                    "\ngetting RequestType");
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	RequestType.add(jsonArray.getString(i));
			                }
			            }
						
					    if(jsonObject.has("ProviderAuditID"))
			            {
			                 jsonArray=jsonObject.getJSONArray("ProviderAuditID");
			                 System.out.println("Length of ProviderAuditID:"+jsonArray.length()+
			                                    "\ngetting ProviderAuditID");
			                 for(int i=0;i<jsonArray.length();i++)
			                 {
			                	 ProviderAuditID.add(jsonArray.getString(i));
			                 } 
			            }
					    
					    if(jsonObject.has("RequestTime"))
			            {
			               jsonArray = jsonObject.getJSONArray("RequestTime");
			               System.out.println("length of RequestTime:"+jsonArray.length()+"\nGetting RequestTime");
			               
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	RequestTime.add(jsonArray.getString(i));
			                }
			            }
					   
					    if(jsonObject.has("Product"))
			            {
			               jsonArray = jsonObject.getJSONArray("Product");
			               System.out.println("length of Product:"+jsonArray.length()
			                                 +"\nGetting Product");
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	Product.add(jsonArray.getString(i));
			                }
			            }
					    
					    if(jsonObject.has("ProductCode"))
			            {
			               jsonArray = jsonObject.getJSONArray("ProductCode");
			             
			               for(int i=0;i<jsonArray.length();i++)
			                {
			            	   ProductCode.add(jsonArray.getString(i));
			                    System.out.println("ProductCode:"+jsonArray.getString(i));
			                }
			            }
					    
					    if(jsonObject.has("Currency"))
			            {
			                jsonArray=jsonObject.getJSONArray("Currency");

			                System.out.println("length of Currency:"+jsonArray.length()
			                       +"\nGetting Currency");
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	Currency.add(jsonArray.getString(i));
			                }
			            }
					    
					    if(jsonObject.has("Batch"))
			            {
			                jsonArray=jsonObject.getJSONArray("Batch");
			                System.out.println("length of Batch:"+jsonArray.length()
			                                   +"\nGetting Batch");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	Batch.add(jsonArray.getString(i));
			                }
			            }
					    if(jsonObject.has("ReferenceNumber"))
			            {
			                jsonArray=jsonObject.getJSONArray("ReferenceNumber");
			                System.out.println("length of ReferenceNumber:"+jsonArray.length()
			                                   +"\nGetting ReferenceNumber");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	ReferenceNumber.add(jsonArray.getString(i));
			                }
			            }
					    if(jsonObject.has("TopUpValue"))
			            {
			                jsonArray=jsonObject.getJSONArray("TopUpValue");
			                System.out.println("length of TopUpValue:"+jsonArray.length()
			                                   +"\nGetting TopUpValue");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	TopUpValue.add(jsonArray.getString(i));
			                }
			            }
					    
					    if(jsonObject.has("TopUpValueRes"))
			            {
			                jsonArray=jsonObject.getJSONArray("TopUpValueRes");
			                System.out.println("length of TopUpValueRes:"+jsonArray.length()
			                                   +"\nGetting TopUpValueRes");
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	TopUpValueRes.add(jsonArray.getString(i));
			                }
			            } 
					    if(jsonObject.has("TopUpValuePro"))
			            {
			                jsonArray=jsonObject.getJSONArray("TopUpValuePro");
			                System.out.println("length of TopUpValuePro:"+jsonArray.length()
			                                   +"\nGetting TopUpValuePro");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	TopUpValuePro.add(jsonArray.getString(i));
			                }
			            }
					    if(jsonObject.has("TransactionResponseCode"))
			            {
			                jsonArray=jsonObject.getJSONArray("TransactionResponseCode");
			                System.out.println("length of TransactionResponseCode:"+jsonArray.length()
			                                   +"\nGetting TransactionResponseCode");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	TransactionResponseCode.add(jsonArray.getString(i));
			                }
			            }
					    
					    if(jsonObject.has("TransactionResponseDescription"))
			            {
			                jsonArray=jsonObject.getJSONArray("TransactionResponseDescription");
			                System.out.println("length of TransactionResponseDescription:"+jsonArray.length()
			                                   +"\nGetting TransactionResponseDescription");
			                
			                for(int i=0;i<jsonArray.length();i++)
			                {
			                	TransactionResponseDescription.add(jsonArray.getString(i));
			                }
			            }
					    
					    System.out.println("=================>Printing Transactions");
			            System.out.println("Size:"+ProviderProductRequestID.size());
			            
			             for(int i=0;i<ProviderProductRequestID.size();i++)
			             {
			                  System.out.println("ProviderProductRequestID:"+ProviderProductRequestID.get(i));
			                  System.out.println("ProductType:"+ProductType.get(i));
			                  System.out.println("RequestType"+RequestType.get(i));
			                  System.out.println("ProviderAuditID:"+ProviderAuditID.get(i));
			                  System.out.println("RequestTime:"+RequestTime.get(i));
			                  System.out.println("Product:"+Product.get(i));
			                  System.out.println("ProductCode:"+ProductCode.get(i));
			                  System.out.println("Currency:"+Currency.get(i));
			                  System.out.println("Batch:"+Batch.get(i));
			                  System.out.println("ReferenceNumber:"+ReferenceNumber.get(i));
			                  System.out.println("TopUpValue:"+TopUpValue.get(i));
			                  System.out.println("TopUpValueRes:"+TopUpValueRes.get(i));
			                  System.out.println("TopUpValuePro :"+TopUpValuePro.get(i));
			                  System.out.println("TransactionResponseCode :"+TransactionResponseCode.get(i));
			                  System.out.println("TransactionResponseDescription:"+TransactionResponseDescription.get(i));
			                  System.out.println("Transaction Summary:"+TransactionResponseDescription.get(i));
			                  System.out.println("=====================");
			                  
			             }
			             
			           transactionArray=new ArrayList<TransactionDetails>(); 
			           
			           for(int i=0;i<ProviderProductRequestID.size();i++)
			           {   
			        	   TransactionDetails transactionDetails=new TransactionDetails();
			        	   
			        	    transactionDetails.setProviderProductRequestID(ProviderProductRequestID.get(i));
			        	    transactionDetails.setProductType(ProductType.get(i));
			        	   
			        	    transactionDetails.setRequestType(RequestType.get(i));
						    transactionDetails.setProviderAuditID(ProviderAuditID.get(i));
						    transactionDetails.setRequestTime(RequestTime.get(i));
							transactionDetails.setProduct(Product.get(i));
							transactionDetails.setProductCode(ProductCode.get(i));
							transactionDetails.setCurrency(Currency.get(i));
							transactionDetails.setBatch(Batch.get(i));
							transactionDetails.setReferenceNumber(ReferenceNumber.get(i));
							//transactionDetails.setTopUpValue(""+Double.parseDouble(TopUpValue.get(i))/100);
							transactionDetails.setTopUpValue(TopUpValue.get(i));
							transactionDetails.setTopUpValueRes(TopUpValueRes.get(i));
							transactionDetails.setTopUpValuePro(TopUpValuePro.get(i));
							transactionDetails.setTransactionResponseCode(TransactionResponseCode.get(i));
							transactionDetails.setTransactionResponseDescription(TransactionResponseDescription.get(i));
							
							transactionArray.add(transactionDetails);
			           }
			           
			            handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								Activity activity=(Activity)mContext;
								
								if(transactionArray.size()>0)
								{
									if(transactionQuerySearch)
									{
										    transactionQueryDialog.dismiss(); 
											Bundle bundle=new Bundle();
											bundle.putString("productname", transactionArray.get(0).getProduct());
											bundle.putString("requesttime",transactionArray.get(0).getRequestTime());
											bundle.putString("topupvalue",transactionArray.get(0).getTopUpValue());
											bundle.putString("referencenumber",transactionArray.get(0).getReferenceNumber());
											bundle.putString("transactionsummary",transactionArray.get(0).getTransactionResponseDescription());
											
											activity.startActivityForResult(new Intent(mContext,TransactionDetailsActivity.class).putExtras(bundle), 22); 
										 
									}
									else
									{
										 
										AppData.transactionArray=transactionArray;
										activity.startActivityForResult(new Intent(mContext,TransactionList.class), 22);
										
									}
								}
								else
								{
									Toast.makeText(mContext, "No Record Found",Toast.LENGTH_SHORT).show(); 
								}
								
								
								
							 
							}
						});
					}
		            
					else
					{
						handler.post(new Runnable()
						{
							
							public void run() 
							{
								// TODO Auto-generated method stub
								pd.dismiss();
								try 
								{
									Toast.makeText(mContext,jsonObject.getString("ResponseDescription"),Toast.LENGTH_LONG).show();
								}
								catch (JSONException e) 
								{
									e.printStackTrace();
								}
							}
						});
					} 
				}
				catch (final Exception e)
				{	 
					handler.post(new Runnable()
					{ 
						public void run() 
						{
							pd.dismiss();
							
							Toast.makeText(mContext,e.getMessage(),Toast.LENGTH_LONG).show();
						}
					});
					 
				}
		 
	}

}
